<script setup>
import { ref } from 'vue';
import { showDialog } from 'vant';
import {get, post} from '../util/request.js';
import { useRouter } from "vue-router";
import { showToast } from 'vant';

const router = useRouter();
const user = ref({});
const canSubmit = ref(false);

const back = () => {
  window.location.reload()
  history.back();
}

const sendCode = () => {
  //发送短信验证码
  get("sms/find", { phone: user.value.phone }).then(r => {
    if (r.code == 0) {
      showToast('验证码已发送到您的手机，请查收！');
    } else {
      showToast(r.data);
    }
  })
}


const checkNewPass = () => {
  if (user.value.newPassword !== user.value.confirmPassword) {
    showDialog({
      title: '密码不一致',
      message: '新密码与确认密码不一致，请重新输入！',
    });
    return;
  }
  canSubmit.value = true;
};

const resetPassword = () => {
  // 发送重置密码请求
  post("user/reset", user.value).then((r) => {
    if (r.code === 0) {
      showToast('密码重置成功，请使用新密码登录！');
      router.push("/");
    } else {
      showDialog({
        title: '重置失败',
        message: r.data,
      });
    }
  });//演示一下
};
</script>
<!-- 忘记密码页面模板 -->
<template>
  <van-nav-bar
      title="忘记密码"
      left-text="返回"
      left-arrow
      @click-left="back"
  />
  <div>
    <van-form @submit="resetPassword">
      <van-cell-group inset>
        <van-field
            v-model="user.phone"
            label="手机号"
            placeholder="请输入绑定的手机号"
            :rules="[{ required: true, message: '请输入手机号' }]"
        />
        <van-field
            v-model="user.code"
            center
            :rules="[{ required: true, message: '请输入验证码' }]"
            clearable
            label="验证码"
            placeholder="请输入验证码"
        >
          <template #button>
            <van-button size="small" type="primary" @click="sendCode">发送验证码</van-button>
          </template>
        </van-field>
        <van-field
            v-model="user.newPassword"
            type="password"
            :rules="[{ required: true, message: '请设置新密码' }]"
            label="新密码"
            placeholder="请输入新密码"
        />
        <van-field
            v-model="user.confirmPassword"
            type="password"
            :rules="[{ required: true, message: '请确认新密码' }]"
            label="确认新密码"
            placeholder="请再次输入新密码"
            @change="checkNewPass"
        />
      </van-cell-group>
      <van-button
          type="primary"
          round
          block
          native-type="submit"
          :disabled="!canSubmit"
          class="reset-btn"
      >重置密码</van-button>
    </van-form>
<!--   :disabled="!canSubmit"   所有必填项都满足条件时才允许提交-->
  </div>
</template>